import { Controller, Context } from 'egg'

export default class AuthController extends Controller {
  constructor(ctx: Context) {
    super(ctx)

    // this.createRule = {
    //   // email: { type: 'email' },
    //   password: {
    //     type: 'password',
    //     // compare: 're-password',
    //     min: 1,
    //   },
    // }
  }

  /**
   * validate rule see: https://github.com/node-modules/parameter#rule.
   */
  async validateCreate() {
    // this.ctx.validate(this.createRule)
    await this.service.user.create({ username: 'test1', password: '1' })
  }

  async currentUser() {
    const { ctx } = this
    ctx.body = ctx.state.user
  }

  async sign() {
    const { ctx } = this
    const { username, password, service } = ctx.request.body
    if (!username) throw new Error('need username.')
    if (!password) throw new Error('need password.')
    if (!service) {
      // throw new Error('authentication login type lost!')
    }
    const accessToken = await this.service.user.sign({ username, password, service })
    ctx.body = { accessToken }
  }

  async decode() {
    const { ctx } = this
    ctx.body = await this.service.user.decode(ctx.accessToken)
  }

  async verify() {
    const { ctx } = this
    ctx.body = await this.service.user.verify(ctx.accessToken)
  }
}
